package com.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.bean.DisciplinaBean;

public class DisciplinaDao {

	public static final String TABELA = "disciplina";

	public static final String COLUNA_DIS_UNI_ID = "uni_id";
	public static final String COLUNA_DIS_ID = "dis_id";
	public static final String COLUNA_DIS_NOME = "dis_nome";

	public long insert(SQLiteDatabase escola, DisciplinaBean disBean){

		ContentValues valores = new ContentValues();
		valores.put(COLUNA_DIS_UNI_ID, disBean.getUnidade().getId());
		valores.put(COLUNA_DIS_NOME, disBean.getNome());

		return escola.insert(TABELA, null, valores);

	}

	public long update(SQLiteDatabase escola, DisciplinaBean disBean){

		ContentValues valores = new ContentValues();
		valores.put(COLUNA_DIS_NOME, disBean.getNome());

		return escola.update(TABELA, valores, COLUNA_DIS_UNI_ID + " = " + disBean.getUnidade().getId() + 
				" AND " + COLUNA_DIS_ID + " = " + disBean.getId(), null);

	}

	public boolean delete(SQLiteDatabase escola, DisciplinaBean disBean){
		return escola.delete(TABELA, COLUNA_DIS_UNI_ID + " = " + disBean.getUnidade().getId() + 
				" AND " + COLUNA_DIS_ID + "=" + disBean.getId(), null) > 0;
	}

	public DisciplinaBean buscaPorCodigo(SQLiteDatabase escola, long unidadeId, long rowId){

		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT * ");
		sql.append("   FROM " + TABELA );
		sql.append("  WHERE "+ COLUNA_DIS_UNI_ID + "=" + unidadeId );
		sql.append("    AND "+ COLUNA_DIS_ID + "=" + rowId);

		DisciplinaBean disBean = new DisciplinaBean();

		Cursor cursor = escola.rawQuery(sql.toString(), null);

		if(cursor.getCount() > 0){

			cursor.moveToFirst();

			disBean.getUnidade().setId(cursor.getInt(cursor.getColumnIndex(COLUNA_DIS_UNI_ID)));
			disBean.setId(cursor.getInt(cursor.getColumnIndex(COLUNA_DIS_ID)));  
			disBean.setNome(cursor.getString(cursor.getColumnIndex(COLUNA_DIS_NOME)));

			cursor.close();

			return disBean;

		} else{

			cursor.close();
			return null;

		}

	}

	public List<DisciplinaBean> getAll(SQLiteDatabase escola, long unidadeId){

		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT * FROM " + TABELA + " WHERE " + COLUNA_DIS_UNI_ID + " = '" + unidadeId + "' ");

		List<DisciplinaBean> disList = new ArrayList<DisciplinaBean>();

		Cursor cursor = escola.rawQuery(sql.toString(), null);

		while(cursor.moveToNext()){

			DisciplinaBean disBean = new DisciplinaBean();

			disBean.getUnidade().setId(cursor.getInt(cursor.getColumnIndex(COLUNA_DIS_UNI_ID)));
			disBean.setId(cursor.getInt(cursor.getColumnIndex(COLUNA_DIS_ID)));
			disBean.setNome(cursor.getString(cursor.getColumnIndex(COLUNA_DIS_NOME)));

			disList.add(disBean);

		}

		cursor.close();
		return disList;

	}

}